import React, { useState, useEffect } from 'react';
import { Card, Row, Col, Select, Spin, message, Typography, Statistic, Divider } from 'antd';
import ReactECharts from 'echarts-for-react';
import { dataAPI } from '../services/api';
import MainLayout from '../components/Layout/MainLayout';

const { Title, Text } = Typography;
const { Option } = Select;

interface FundOption {
  code: string;
  name: string;
}

interface FundDetailInfo {
  fund_code: string;
  fund_name: string;
  fund_type: string;
  fund_company: string;
  manager_name: string;
  establishment_date: string;
  fund_scale: number;
  management_fee: number;
  custody_fee: string;
  benchmark: string;
  investment_objective: string;
  investment_scope: string;
  risk_return_characteristics: string;
}

interface NavHistoryData {
  date: string;
  net_value: number;
  accumulated_value: number;
}

const FundDetailChart: React.FC = () => {
  const [fundOptions, setFundOptions] = useState<FundOption[]>([]);
  const [selectedFund, setSelectedFund] = useState<string>('');
  const [fundDetail, setFundDetail] = useState<FundDetailInfo | null>(null);
  const [navHistory, setNavHistory] = useState<NavHistoryData[]>([]);
  const [loading, setLoading] = useState(false);
  const [optionsLoading, setOptionsLoading] = useState(true);

  // 获取基金列表用于下拉框
  useEffect(() => {
    const fetchFundOptions = async () => {
      try {
        setOptionsLoading(true);
        const data = await dataAPI.getFundListForSelect();
        setFundOptions(data);
      } catch (error) {
        message.error('获取基金列表失败');
        console.error('Error fetching fund options:', error);
      } finally {
        setOptionsLoading(false);
      }
    };

    fetchFundOptions();
  }, []);

  // 获取基金详细信息
  const fetchFundDetail = async (fundCode: string) => {
    try {
      const response = await dataAPI.getFundDetailInfo(fundCode);
      
      // 处理API响应结构
      if (response && response.status === 'success' && response.data) {
        // 转换字段名以匹配前端期望的格式
        const formattedData = {
          fund_code: response.data.fund_code,
          fund_name: response.data.fund_name,
          fund_type: response.data.fund_type,
          fund_company: response.data.fund_company,
          manager_name: response.data.fund_manager, // API返回fund_manager，前端期望manager_name
          establishment_date: response.data.establishment_date,
          fund_scale: response.data.fund_size || 0, // API返回fund_size，前端期望fund_scale
          management_fee: response.data.management_fee || 0,
          custody_fee: response.data.custodian_fee || '', // API返回custodian_fee，前端期望custody_fee
          benchmark: response.data.benchmark || '',
          investment_objective: response.data.investment_objective || '',
          investment_scope: response.data.investment_scope || '',
          risk_return_characteristics: response.data.risk_return_characteristics || ''
        };
        setFundDetail(formattedData);
      } else {
        console.warn('基金详细信息数据格式异常:', response);
        setFundDetail(null);
      }
    } catch (error) {
      message.error('获取基金详细信息失败');
      console.error('Error fetching fund detail:', error);
      setFundDetail(null);
    }
  };

  // 获取基金历史净值数据
  const fetchNavHistory = async (fundCode: string) => {
    try {
      const response = await dataAPI.getFundNavHistoryChart(fundCode);
      
      // 处理API响应结构
      if (response && response.status === 'success' && Array.isArray(response.data)) {
        // 转换字段名以匹配前端期望的格式
        const formattedData = response.data.map((item: any) => ({
          date: item.date,
          net_value: item.unit_nav,
          accumulated_value: item.accumulated_nav
        }));
        setNavHistory(formattedData);
      } else {
        console.warn('基金历史净值数据格式异常:', response);
        setNavHistory([]);
      }
    } catch (error) {
      message.error('获取基金历史净值数据失败');
      console.error('Error fetching nav history:', error);
      setNavHistory([]);
    }
  };

  // 处理基金选择变化
  const handleFundChange = async (fundCode: string) => {
    setSelectedFund(fundCode);
    setLoading(true);
    
    try {
      await Promise.all([
        fetchFundDetail(fundCode),
        fetchNavHistory(fundCode)
      ]);
    } finally {
      setLoading(false);
    }
  };

  // 准备图表数据
  const dates = navHistory.map(item => item.date);
  const netValues = navHistory.map(item => item.net_value);
  const accumulatedValues = navHistory.map(item => item.accumulated_value);

  // ECharts配置
  const chartOption = {
    title: {
      text: '基金净值走势',
      left: 'center'
    },
    tooltip: {
      trigger: 'axis',
      formatter: function (params: any) {
        let result = params[0].axisValue + '<br/>';
        params.forEach((param: any) => {
          result += param.marker + param.seriesName + ': ' + (param.value ? param.value.toFixed(4) : '-') + '<br/>';
        });
        return result;
      }
    },
    legend: {
      data: ['单位净值', '累计净值'],
      top: 30
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      top: '15%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: dates
    },
    yAxis: {
      type: 'value',
      axisLabel: {
        formatter: '{value}'
      }
    },
    series: [
      {
        name: '单位净值',
        type: 'line',
        smooth: true,
        data: netValues,
        itemStyle: {
          color: '#1890ff'
        },
        lineStyle: {
          color: '#1890ff'
        }
      },
      {
        name: '累计净值',
        type: 'line',
        smooth: true,
        data: accumulatedValues,
        itemStyle: {
          color: '#52c41a'
        },
        lineStyle: {
          color: '#52c41a'
        }
      }
    ]
  };

  return (
    <MainLayout>
      <Title level={2}>基金详情分析</Title>
      
      {/* 基金选择 */}
      <Card style={{ marginBottom: 24 }}>
        <Row gutter={16} align="middle">
          <Col span={4}>
            <Text strong>选择基金：</Text>
          </Col>
          <Col span={8}>
            <Select
              style={{ width: '100%' }}
              placeholder="请从下拉列表中选择基金"
              loading={optionsLoading}
              onChange={handleFundChange}
              value={selectedFund || undefined}
              popupMatchSelectWidth={false}
              styles={{
                popup: {
                  root: { minWidth: 400 }
                }
              }}
            >
              {fundOptions.map(fund => (
                <Option key={fund.code} value={fund.code}>
                  {fund.code} - {fund.name}
                </Option>
              ))}
            </Select>
          </Col>
          <Col span={12}>
            <Text type="secondary" style={{ fontSize: '12px' }}>
              提示：请从下拉列表中选择基金，不支持手动输入
            </Text>
          </Col>
        </Row>
      </Card>

      {selectedFund && (
        <Spin spinning={loading}>
          {/* 基金基本信息 */}
          {fundDetail && (
            <Card title="基金基本信息" style={{ marginBottom: 24 }}>
              <Row gutter={[16, 16]}>
                <Col span={6}>
                  <Statistic title="基金代码" value={fundDetail.fund_code} />
                </Col>
                <Col span={6}>
                  <Statistic title="基金名称" value={fundDetail.fund_name} />
                </Col>
                <Col span={6}>
                  <Statistic title="基金类型" value={fundDetail.fund_type} />
                </Col>
                <Col span={6}>
                  <Statistic title="基金公司" value={fundDetail.fund_company} />
                </Col>
                <Col span={6}>
                  <Statistic title="基金经理" value={fundDetail.manager_name} />
                </Col>
                <Col span={6}>
                  <Statistic title="成立日期" value={fundDetail.establishment_date} />
                </Col>
                <Col span={6}>
                  <Statistic 
                    title="基金规模(亿元)" 
                    value={fundDetail.fund_scale} 
                    precision={2}
                  />
                </Col>
                <Col span={6}>
                  <Statistic 
                    title="管理费率(%)" 
                    value={fundDetail.management_fee} 
                    precision={2}
                  />
                </Col>
              </Row>
              
              <Divider />
              
              <Row gutter={[16, 16]}>
                <Col span={24}>
                  <Text strong>业绩比较基准：</Text>
                  <Text>{fundDetail.benchmark}</Text>
                </Col>
                <Col span={24}>
                  <Text strong>投资目标：</Text>
                  <Text>{fundDetail.investment_objective}</Text>
                </Col>
                <Col span={24}>
                  <Text strong>投资范围：</Text>
                  <Text>{fundDetail.investment_scope}</Text>
                </Col>
                <Col span={24}>
                  <Text strong>风险收益特征：</Text>
                  <Text>{fundDetail.risk_return_characteristics}</Text>
                </Col>
              </Row>
            </Card>
          )}

          {/* 历史净值曲线图 */}
          {navHistory.length > 0 && (
            <Card title="历史净值走势" style={{ marginBottom: 24 }}>
              <div style={{ height: 400 }}>
                <ReactECharts option={chartOption} style={{ height: '100%', width: '100%' }} />
              </div>
            </Card>
          )}
        </Spin>
      )}
    </MainLayout>
  );
};

export default FundDetailChart;